package qf.filter;

import qf.dao.UserDao;
import qf.dao.daoImpl.UserDaoImpl;
import qf.pojo.User;
import qf.service.UserService;
import qf.service.serviceImpl.UserServiceImpl;
import qf.utils.Base64Utils;
import qf.utils.Constants;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 86198
 * @version V1.0
 * @Project Java_qf
 * @Package qf.filter
 * @Description:
 * @Date 2022/5/22 17:48
 */
@WebFilter("/login.jsp")
public class AutoFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();

        Object loginUser = session.getAttribute("loginUser");
        if (loginUser != null) {
            response.sendRedirect("/index.jsp");
            return;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            String content=null;
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(Constants.AUTO_NAME)) {
                    content=cookie.getValue();
                }
            }
            if (content != null) {
                content = Base64Utils.decode(content);
                String[] split = content.split(Constants.FLAG);
                String username = split[0];
                String password = split[1];

                UserDao userDao = new UserDaoImpl();
                UserService userservice = new UserServiceImpl(userDao);

                User users = userservice.findUsers(username, password);

                if (users != null) {
                    session.setAttribute("loginUser",users);
                    response.sendRedirect(request.getContextPath()+"/index.jsp");
                }else {
                    filterChain.doFilter(servletRequest,servletResponse);
                }

            }else {
                filterChain.doFilter(servletRequest,servletResponse);
            }
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
